package ru.eas.tetris;

import java.awt.Color;
import java.util.ArrayList;
import java.util.List;

/**
 * @author aesipov
 */
public class Well
{
    private int         width;
    private int         height;
    private boolean[][] squares;
    private Color[][]   colors;

    public Well(int width,
                int height)
    {
        this.width = width;
        this.height = height;
        squares = new boolean[width][height];
        colors = new Color[width][height];
    }

    public int getWidth()
    {
        return width;
    }

    public int getHeight()
    {
        return height;
    }

    public boolean isOverflown()
    {
        for (int i = 0; i < width; i++) {
             if (squares[i][0]) {
                return true;
             }
        }
        return false;
    }

    public boolean isSquare(int x,
                            int y)
    {
        return squares[x][y];
    }

    public Color getColor(int x,
                          int y)
    {
        return colors[x][y];
    }

    public void changeState(Figure figure)
    {
        for (Square square : figure.getSquares())
        {
            squares[square.x][square.y] = true;
            colors[square.x][square.y] = figure.getColor();
        }
    }


    public List<Integer> getCompleteLines() {
        List<Integer> result = new ArrayList<Integer>();
        for (int i = 0; i < height; i++) {
            if (isLineComplete(i)) {
                result.add(i);
            }
        }
        return result;
    }

    public void removeLines(List<Integer> lineNumbers) {
        for (Integer lineNumber : lineNumbers) {
            removeLine(lineNumber);
        }
    }

    private void removeLine(int lineNumber) {
        for (int i = lineNumber - 1; i >= 0; i--) {
            moveLineDown(i);
        }
    }

    private void moveLineDown(int lineNumber) {
        for (int i = 0; i < width; i++) {
            squares[i][lineNumber + 1] = squares[i][lineNumber];
        }
    }

    private boolean isLineComplete(int lineNumber) {
        for (int column = 0; column < width; column++) {
            if (!squares[column][lineNumber]) {
                return false;       
            }
        }
        return true;
    }

    public void clear() {
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                squares[i][j] = false;
            }
        }
    }
}
